package cn.jussi.mvcproject.dao;

import java.sql.Connection;
import java.util.List;

import cn.jussi.mvcproject.model.User;

public class UserDaoImpl extends BaseDao<User> implements UserDao {

	@Override
	public int save(User user) {
		String sql = "insert into users(username, password, phone_num, address, reg_date) values(?,?,?,?,?)";
		return super.update(sql, user.getUsername(), user.getPhoneNum(), user.getPhoneNum(), user.getAddress(), user.getRegDate());
	}

	@Override
	public int deleteUserById(int id) {
		String sql = "delete from users where id=?";
		return super.update(sql, id);
	}

	@Override
	public int updateUserById(User user) {
		String sql = "update users set username=?, password=?, phone_num=?, address=? where id=?";
		return super.update(sql, user.getUsername(), user.getPassword(), user.getPhoneNum(), user.getAddress(), user.getId());
	}

	@Override
	public User get(int id) {
		String sql = "select id, username, password, phone_num phoneNum, address, reg_date regDate from users where id=?";
		return super.get(sql, id);
	}

	@Override
	public User get(Connection conn, int id) {
		String sql = "select id, username, password, phone_num phoneNum, address, reg_date regDate from users where id=?";
		return super.get(conn, sql, id);
	}
	
	@Override
	public List<User> getListAll() {
		String sql = "select id, username, password, phone_num phoneNum, address, reg_date regDate from users";
		return super.getList(sql);
	}

	@Override
	public int getCountByName(String username) {
		String sql = "Select count(*) from users where username=?";
		return (int) super.getValue(sql, username);
	}

	@Override
	public List<User> query(String username, String address, String phoneNum) {
		String sql = "select id, username, password, phone_num phoneNum, address, reg_date regDate from users where 1=1";
		if(username!=null && !"".equals(username)) {
			sql = sql+" and username like '%"+username+"%'";
		} 
		if(address!=null && !"".equals(address)) {
			sql = sql+" and address like '%"+address+"%'";
		} 
		if(phoneNum!=null && !"".equals(phoneNum)) {
			sql = sql+" and phone_num like '%"+phoneNum+"%'";
		} 
		//System.out.println(sql);
		return super.getList(sql);
	}

	@Override
	public User getUserByNameAndKey(String username, String password) {
		String sql = "select id, username, password, phone_num phoneNum, address, reg_date regDate from users where username=? and password=?";		
		return super.get(sql, username, password);
	}

}
